import { strSelfSort, isChinese, sortChinese } from './utils/sort'

export interface stuType {
  stuname: string
  age: number
  address: string
}
/**
 * 泛型类
 */
// extends object extends keyof
export class ArrayList<T = any> {
  public element: Array<T>
  constructor() {
    this.element = []
  }
  public index: number = 0
  public add(ele: T) {
    this.checkIndex()
    this.element[this.index++] = ele
  }
  public checkIndex() {
    if (this.index < 0) {
      throw new Error('数组下标不能为零')
    }
  }
  get(index: number): T {
    return this.element[index]
  }
  show() {
    this.element.forEach(ele => {
      console.log(ele)
    })
  }

  remove(value: number): number
  remove(value: T): T
  remove(value: any): any {
    this.element = this.element.filter((ele, index) => {
      if (typeof value === 'number') {
        return value !== index
      } else {
        return value !== ele
      }
    })
    return value
  }
}
export const stuOne: stuType = { stuname: 'wnagwu', age: 23, address: 'beijing' }
export const stuTwo: stuType = { stuname: 'lisi', age: 39, address: 'shanghai' }
export const stuThree: stuType = { stuname: 'liuqi', age: 31, address: 'nanjing' }

/**
 * 泛型接口
 */
interface List<T> {
  add(ele: T): void
  get(index: number): T
  size(): number
  remove(value: T): T
}

/**
 * 泛型函数
 */
// 快速排序算法思路：
// 1．先从数列中取出一个数作为基准数。
// 2．分区过程，将比这个数大的数全放到它的右边，小于或等于它的数全放到它的左边。
// 3．再对左右区间重复第二步，直到各区间只有一个数。

export function quickSort<T>(arr: Array<T>): T[] {
  if (arr.length < 2) {
    return arr
  }

  var left: Array<T> = []
  var right: Array<T> = []
  var mid = arr.splice(Math.floor(arr.length / 2), 1)[0]

  for (var i = 0; i < arr.length; i++) {
    if (arr[i] < mid) {
      left.push(arr[i])
    } else {
      right.push(arr[i])
    }
  }
  return quickSort(left).concat(mid, quickSort(right))
}

/**
 * 泛型函数重载
 */
// export function sort(data: string, count?: number): string
// export function sort(data: string[], count?: number): string[]
// export function sort(data: number[], count?: number): number[]
export function sort<T>(data: T, count?: number): T
export function sort(data: any, count: number = 5): any {
  if (typeof data === 'string') {
    //如果是字符串
    return strSelfSort(data, count) // 按照字符串自排序
  }
  if (data instanceof Array) {
    //如果data是数组
    if (isChinese(data)) {
      //如果是中文数组
      return sortChinese(data)
    }
    let newArr = data.map(item => {
      return typeof item === 'string' ? strSelfSort(item) : item
    })
    //英文、数字数组排序
    return quickSort(newArr as any)
  }
}
